package com.niit.project.service.impl;

import com.niit.project.dao.UserGoodsDao;
import com.niit.project.dao.impl.UserGoodsDaoImpl;
import com.niit.project.entity.Page;
import com.niit.project.entity.UserGoods;
import com.niit.project.service.UserGoodsService;
import com.niit.project.utils.Dbutils;

import java.util.List;

public class UserGoodsServiceImpl implements UserGoodsService {
    private UserGoodsDao userGoodsDao = new UserGoodsDaoImpl();
    @Override
    public List<UserGoods> showAllByPage(Page page) {
        List<UserGoods> userGoods = null;
        try {
            Dbutils.begin();
            long count = userGoodsDao.selectCount();
            page.setTotalCounts((int)count);
            userGoods = userGoodsDao.selectAll(page);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return userGoods;
    }

    @Override
    public int deleteGoods(int id) {
        int result = 0;
        try {
            Dbutils.begin();
            result = userGoodsDao.delete(id);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }

        return result;

    }

    @Override
    public int addGoods(UserGoods userGoods) {
        int result = 0;
        try {
            Dbutils.begin();
            result = userGoodsDao.insert(userGoods);
            System.out.println("个人模块已添加");
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public UserGoods selectGoodsById(int id) {
        UserGoods userGoods = null;
        try {
            Dbutils.begin();
            userGoods = userGoodsDao.select(id);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return userGoods;
    }

    @Override
    public int modifyGoods(UserGoods userGoods) {
        int result = 0;
        try {
            Dbutils.begin();
            result = userGoodsDao.update(userGoods);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return result;
    }


    @Override
    public UserGoods showSelectSearch(String keyword) {
        UserGoods objects = null;
        try {
            Dbutils.begin();
            objects = userGoodsDao.query(keyword);
            Dbutils.commit();
        } catch (Exception ex) {
            Dbutils.rollback();
            throw new RuntimeException(ex);
        }
        return objects;
    }
}
